#!/usr/bin/python

import sys
import time
import httplib
import json

from urlparse import urlsplit
from optparse import OptionParser

def print_usage():
    print("license-client.py redeem <code> <system> <user>")
    print("license-client.py reset")
    print("license-client.py put <code> <'amount' | 'period'> <amount>")

def main():
    parser = OptionParser()
    #parser.add_option("-s", "--server", dest="server",
    #                  help="write report to FILE", metavar="FILE")
    #parser.add_option("-q", "--quiet",
    #                  action="store_false", dest="verbose", default=True,
   #                   help="don't print status messages to stdout")

    conn = httplib.HTTPConnection(host="127.0.0.1", port=8080,
                                  timeout=10)
    try:
        cmd = sys.argv[1]

        if cmd == "redeem":
            code = sys.argv[2]
            system = sys.argv[3]
            user = sys.argv[4]
            headers = { b'Content-Type': b'application/json' }
            req_body = json.dumps({'code': code,
                                   'system': system,
                                   'user': user})
            conn.request('POST', '/codes/redeemed', req_body, headers)

            resp = conn.getresponse()
            data = resp.read()
            print resp.status, resp.reason
            print data
        elif cmd == "reset":
            method = "reset"
            params = {}
            headers = { b'Content-Type': b'application/json' }
            req_body = json.dumps({'method': method, 'params': params})

            conn.request('POST', '/codes/mgmt', req_body, headers)
            resp = conn.getresponse()
            print resp.status
        else:
            raise Exception()
    except:
        print("Something went wrong. Check usage!")
        print_usage()

    conn.close()

if __name__ == '__main__':
    main()
